
let _Vue = null
export default class VueRouter {
  static install(Vue) {
    // 1.判断当前插件是否被安装
    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true
    // 2.把Vue的构造函数记录在全局
    _Vue = Vue
    /**
     * 3.把创建Vue的实例是传入的router对象注入到Vue实例
     * 使用混入，给所有的Vue实例混入一个选项，通过 beforeCreate 钩子来获取到Vue实例
     */
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

  constructor(options) {
    this.options = options
    this.mode = options.mode || 'hash'
    // 存储解析后的路由规则
    this.routeMap = {}
    // 响应式属性
    this.data = _Vue.observable({
      // 存储当前的路由地址
      current: '/'
    })
  }

  init() {
    this.createRouteMap()
    this.initComponent(_Vue)
    this.initEvent()
  }

  createRouteMap() {
    // 遍历所有的路由规则，把路由规则解析成键值对的形式存储到routeMap中
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponent(Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      // template: '<a :href="to"><solt></solt></a>'
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on:{
            click: this.clickhander
          }
        }, [this.$slots.default])
      },
      methods: {
        clickhander(e){
          // history hash 模式处理
          if(this.$router.mode === 'history'){
            history.pushState({}, '', this.to)
          }else {
            location.hash = this.to
          }
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })

    let self = this
    Vue.component('router-view', {
      render(h) {
        const component = self.routeMap[self.data.current]
        return h(component)
      }
    })
  }

  initEvent() {
    window.addEventListener('popstate', () => {
      this.data.current = location.pathname
    })
    
    window.addEventListener('hashchange', () => {
      this.data.current = location.hash.slice(1)
    })
  }

}
